package sjy.controller;

import sjy.dao.ConnectMysql;
import sjy.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        System.out.println("get");
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        System.out.println("post");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String pw = request.getParameter("password");
        User user = new User(name,pw);
        ConnectMysql connectMysql = new ConnectMysql();
        boolean flag;
        try {
            flag = connectMysql.ConnectMysql(user);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(flag)
        {
//            System.out.println("登录成功");
            request.setAttribute("result", "登录成功，欢迎"+name);
            request.getSession().setAttribute("name",name);
            request.getRequestDispatcher("/LoginSuccess(main).jsp").forward(request,response);
        }
        else
        {
//            System.out.println("登录失败");
            request.setAttribute("result", "登录失败，账号或密码错误！");
//            request.getSession().setAttribute("error", "账号或者密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }
}
